/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
 */
package td.client.presenter;

import java.util.ArrayList;

import td.client.ClientState;
import td.client.place.NameTokens;
import td.client.presenter.handlers.EditUiHandlers;
import td.client.presenter.handlers.EditUiHandlers.MyView;
import td.domain.Thought;
import td.domain.Topic;
import td.pt.RightNavigationPresenter;
import td.pt.event.EditEvent;
import td.pt.event.EditEvent.EditHandler;
import td.pt.event.ReferenceThoughtsEvent;
import td.pt.event.ReferenceThoughtsEvent.ReferenceThoughtsHandler;

import com.google.gwt.user.client.Window;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.Proxy;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;

/**
 * @author Artem Shamsutdinov
 * 
 */
public class EditPresenter extends Presenter<MyView, EditPresenter.MyProxy>
		implements EditUiHandlers {

	@ProxyStandard
	// @NameToken(NameTokens.edit)
	// @UseGatekeeper(EditGatekeeper.class)
	public interface MyProxy extends Proxy<EditPresenter> {
	}

	@Inject
	ClientState state;

	EditHandler editHandler = new EditHandler() {
		@Override
		public void onEdit(EditEvent event) {
			Thought draft = state.getThinker().getDraft();
			Thought specifiedThought = event.getThought();
			if (specifiedThought != null) {
				if (draft != null) {
					Window.alert("Cannot edit another thought while you have an unsaved draft, displaying the existing draft.");
					loadFromThought(draft);
				} else {
					loadFromThought(specifiedThought);
				}
			} else if (draft != null) {
				loadFromThought(draft);
			} else {
				if (draft == null) {
					draft = newDraft();
				}
				Topic specifiedTopic = event.getTopic();
				if (specifiedTopic != null) {
					draft.setTopic(specifiedTopic);
				}
				loadFromThought(draft);
			}
			state.setCurrentThought(null);
			state.setCurrentPlace(NameTokens.notfound);
			state.setNeedVerificationOnLogout(true);
		}
	};

	void loadFromThought(Thought thought) {
		if (thought.getTopic() != null) {
			getView().getTopic().setText(thought.getTopic().getName());
		} else {
			getView().getTopic().setText("Topic to be determined ...");
		}
		getView().getTitle().setText(thought.getTitle());
		getView().getSynopsis().setText(thought.getSynopsis());
		getView().getThoughtBody().setText(thought.getText());
		state.setCurrentThought(thought);
	}

	Thought newDraft() {
		Thought draft = new Thought();
		draft.setThinker(state.getThinker());
		state.getThinker().setDraft(draft);
		return draft;
	}

	ReferenceThoughtsHandler referenceAThoughtHandler = new ReferenceThoughtsHandler() {

		@Override
		public void onReferenceAThought(ReferenceThoughtsEvent event) {
			if (state.getThinker().getDraftReferences() == null) {
				state.getThinker().setDraftReferences(new ArrayList<Thought>());
			}
			state.getThinker().getDraftReferences()
					.addAll(event.getThoughtsToReference());
			StringBuilder references = new StringBuilder();
			for (Thought reference : state.getThinker().getDraftReferences()) {
				references.append(" '" + reference.getTitle() + "'");
			}
			getView().getReferences().setText(references.toString());
		}
	};

	@Inject
	public EditPresenter(final EventBus eventBus, final MyView view,
			final MyProxy proxy) {
		super(eventBus, view, proxy);
	}

	@Override
	protected void revealInParent() {
		RevealContentEvent.fire(this, RootPresenter.SLOT_content, this);
	}

	@Override
	protected void onBind() {
		super.onBind();
		registerHandler(getEventBus().addHandler(EditEvent.TYPE, editHandler));
		registerHandler(getEventBus().addHandler(ReferenceThoughtsEvent.TYPE,
				referenceAThoughtHandler));
	}

	@Override
	protected void onReset() {
		saveDraft();
		super.onReset();
	}

	@Inject
	RightNavigationPresenter.MyView rightNavView;

	@Override
	protected void onHide() {
		super.onHide();
		saveDraft();
	}

	void saveDraft() {
		Thought draft = state.getThinker().getDraft();
		if (draft != null) {
			draft.setText(getView().getThoughtBody().getText());
			draft.setSynopsis(getView().getSynopsis().getText());
			draft.setTitle(getView().getTitle().getText());
		}
	}

}
